package com.lv.suyiyong.hfr.utils.login

import android.app.Activity
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.LifecycleOwner
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.DensityUtil
import com.lv.common.utils.showToast
import com.lv.service.bean.AroutBean
import com.lv.service.event.ThreeLandingEvent
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.moudel.MainViewModel
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig
import com.mobile.auth.gatewayauth.AuthUIConfig
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.ResultCode
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate
import org.json.JSONException
import org.json.JSONObject


/**
 * 作者： ygx
 * 创建日期：2023/7/12 10:11 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：xml文件方便预览
 * 可以通过addAuthRegisterXmlConfig一次性统一添加授权页的所有自定义view
 */

class CustomXmlConfig
    (
    activity: Activity?,
    viewModel: MainViewModel?,
    lifecycleOwner: LifecycleOwner?,
    authHelper: PhoneNumberAuthHelper?,
    tagARouter: AroutBean?
) :
    BaseUIConfig(activity, viewModel, lifecycleOwner, authHelper) {
    private val TAG = "xml样式"
    private var isCheck = false
    private var loginCode = ""
    private val openid = ""
    private var mTagARouter: AroutBean? = null

    private val usrId = ""

    init {
        this.mActivity = activity
        this.mLifecycleOwner = lifecycleOwner
        this.mViewModel = viewModel
        this.mTagARouter = tagARouter
    }

    override fun configAuthPage() {
        LiveEventBus.get(
            ThreeLandingEvent::class.java,
        ).observe(
            mLifecycleOwner
        ) { s ->
            if (s.tag == 0) {
                LogUtils.e("微信回调了")
                mAuthHelper.removeAuthRegisterViewConfig()
                mAuthHelper.quitLoginPage()
            }
        }
        mAuthHelper.removeAuthRegisterXmlConfig()
        mAuthHelper.removeAuthRegisterViewConfig()
        var authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
        if (Build.VERSION.SDK_INT == 26) {
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND
        }
        mAuthHelper.setUIClickListener { code, context, jsonString ->
            var jsonObj: JSONObject? = null
            try {
                if (!TextUtils.isEmpty(jsonString)) {
                    jsonObj = JSONObject(jsonString)
                }
            } catch (e: JSONException) {
                jsonObj = JSONObject()
            }
            when (code) {
                ResultCode.CODE_ERROR_USER_CANCEL -> {
                    Log.e(TAG, "点击了授权页默认返回按钮")
                    mAuthHelper.removeAuthRegisterViewConfig()
                    mAuthHelper.quitLoginPage()
                    mActivity.finish()
                }

                ResultCode.CODE_ERROR_USER_SWITCH -> Log.e(TAG, "点击了授权页默认切换其他登录方式")
                ResultCode.CODE_ERROR_USER_LOGIN_BTN -> if (!jsonObj!!.optBoolean("isChecked")) {
                    showToast("请阅读并勾选页面协议")
                }

                ResultCode.CODE_ERROR_USER_CHECKBOX -> Log.e(
                    TAG,
                    "checkbox状态变为" + jsonObj!!.optBoolean("isChecked")
                )

                ResultCode.CODE_ERROR_USER_PROTOCOL_CONTROL -> Log.e(
                    TAG,
                    "点击协议，" + "name: " + jsonObj!!.optString("name") + ", url: " + jsonObj.optString(
                        "url"
                    )
                )

                ResultCode.CODE_ERROR_USER_CONTROL_CANCEL_BYBTN -> {
                    Log.e(
                        TAG,
                        "用户调用userControlAuthPageCancel后使用左上角返回按钮返回交由sdk接入方控制"
                    )
                    mAuthHelper.quitLoginPage()
                    mActivity.finish()
                }

                ResultCode.CODE_ERROR_USER_CONTROL_CANCEL_BYKEY -> {
                    Log.e(
                        TAG,
                        "用户调用userControlAuthPageCancel后使用物理返回键返回交由sdk接入方控制"
                    )
                    mAuthHelper.quitLoginPage()
                    mActivity.finish()
                }

                else -> {}
            }
        }
        //添加自定义切换其他登录方式
        mAuthHelper.addAuthRegisterXmlConfig(
            AuthRegisterXmlConfig.Builder()
                .setLayout(R.layout.login_other_port, object : AbstractPnsViewDelegate() {
                    override fun onViewCreated(view: View) {
                        findViewById(R.id.tv_third_login).setOnClickListener {
//                            val pIntent = Intent(
//                                mActivity,
//                                LoginActivity::class.java
//                            )
//                            mActivity.startActivity(pIntent)
                            ARouter.getInstance().build(ARoutUtils.LoginActivityURL)
                                .withParcelable(ARoutUtils.AROUT_TAG, mTagARouter).navigation()
                            mActivity.overridePendingTransition(0, 0)
                            mAuthHelper.quitLoginPage()
//                            mActivity.finish()
                        }

                    }
                })
                .build()
        )


        mAuthHelper.setAuthUIConfig(
            AuthUIConfig.Builder()
                .setNavHidden(false)
                .setPrivacyState(false)
//                .setStatusBarHidden(false)
                .setStatusBarColor(Color.WHITE)
                .setNavText("")
                //沉浸式状态栏
                .setNavColor(Color.parseColor("#ffffff"))
//                .setNavTextColor(Color.parseColor("#242424")) //沉浸式状态栏
//                .setNavColor(Color.TRANSPARENT)
                .setStatusBarUIFlag(View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
                .setWebNavColor(Color.parseColor("#ffffff"))
                .setWebNavReturnImgPath("icon_back")
                .setWebNavTextColor(Color.parseColor("#242424"))
                .setWebViewStatusBarColor(Color.parseColor("#ffffff"))
                .setAppPrivacyOne(
                    "《用户协议》",
                    "https://www.suyiyong.cn/YSZZ/yhxy.html?ifshownav=0"
                )
                .setAppPrivacyTwo(
                    "《隐私政策》",
                    "https://www.suyiyong.cn/newYSZC/index.html?ifshownav=0"
                )
                .setAppPrivacyColor(Color.parseColor("#aaaaaa"), Color.parseColor("#ef7b4a"))
                .setAuthPageActIn("in_activity", "out_activity")
                .setAuthPageActOut("in_activity", "out_activity")
//                .setAppPrivacyColor(Color.parseColor("#999999"), Color.parseColor("#ef7b4a")) //隐藏默认切换其他登录方式
                .setSwitchAccHidden(true) //隐藏默认Toast
                .setLogBtnToastHidden(true)

                .setNavReturnImgPath("icon_back")
                .setLightColor(true)
                .setWebNavTextSizeDp(20)
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
                .setLogoImgPath("logo_shap_icon")
                .setLogoScaleType(ImageView.ScaleType.CENTER_CROP)
                .setLogBtnText("本机号码一键登录")
                .setLogoWidth(DensityUtil.dip2px(mActivity, 28f))
                .setLogoHeight(DensityUtil.dip2px(mActivity, 28f))
                .setLogoOffsetY(DensityUtil.dip2px(mActivity, 34f)) //logo高度
                .setNumFieldOffsetY(DensityUtil.dip2px(mActivity, 72f)) //号码高度
                .setSloganOffsetY(DensityUtil.dip2px(mActivity, 87f)) //认证服务高度
                .setLogBtnOffsetY(DensityUtil.dip2px(mActivity, 130f)) //登录按钮高度
                .setPrivacyOffsetY(DensityUtil.dip2px(mActivity, 110f))
                .setUncheckedImgPath("btn_unselected")
                .setCheckedImgPath("btn_selected")
                .setSloganTextColor(Color.parseColor("#999999"))
                .setSloganTextSizeDp(12)
                //                .setSwitchOffsetY(DensityUtil.dip2px(mActivity, 20))//切换按钮高度
                //一键登录按钮三种状态背景示例login_btn_bg.xml
                .setLogBtnBackgroundPath("icon_onekey_sel")
                .setLogBtnHeight(38)
                .setScreenOrientation(authPageOrientation)


//                .setLogoHidden(false)
//                .setSloganHidden(false)

                .create()
        )

    }

//    fun showMyToast(msg: String) {
//        val inflater: LayoutInflater = (mActivity).layoutInflater
//        val view: View = inflater.inflate(com.lv.common.R.layout.toast_custom_view, null)
//        view.findViewById<TextView>(com.lv.common.R.id.tv_title).text = msg
//        ToastUtils.setGravity(Gravity.CENTER_VERTICAL, 0, 0)
//        ToastUtils.showCustomShort(view)
//    }
}